/*
* This is a universal TCP client
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netdb.h>


int create_tcp_client(const char *ip, unsigned short port)
{
	int fd;
	struct sockaddr_in server_addr;
	struct hostent *tmp;
	int ret;

	fd = socket(AF_INET, SOCK_STREAM, 0);
	if(fd == -1){
		perror("socket");
		return -1;
	}

	memset(&server_addr, 0, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(port);
	tmp = gethostbyname(ip);
	if(tmp == NULL){
		perror("gethostbyname");
		return -1;
	}
	memcpy(&server_addr.sin_addr, (struct in_addr *)tmp->h_addr,4);
	ret = connect(fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
	if(ret == -1){
		perror("connect");
		return -1;
	}

	printf("connect success\n");

	return fd;
	
}

int main(int argc, char *argv[])
{
	int fd, ret;
	unsigned short port = 0;
	char buf[1024] = "Hello";

	if(argc != 3){
		fprintf(stderr, "Usage URL[IP] PortNum...\n");
		exit(1);
	}

	port = atoi(argv[2]);
	fd = create_tcp_client(argv[1], port);
	if(fd < 0){
		fprintf(stderr, "create TCP client failed\n");
		exit(-1);
	}

	//ret = send(fd, buf, sizeof(buf), 0);
	//if(ret < 0){
		//perror("send buf");
	//}

	ret = recv(fd, buf, 1024, 0);
	printf("Get MSG : %s\n", buf);
	
	close(fd);
}
